const _ = require('lodash');
const nodemailer = require('nodemailer');
const QcloudSms = require('qcloudsms_js');
import { email as emailConfig, msg as msgConfig } from '../config';
import * as reg from '../reg';

export default {
  isEmtpyObj(o: any) {
    return JSON.stringify(o) === '{}';
  },
  isEmptyString(o: any) {
    return Object.prototype.toString.call(o) === '[object String]' && !o.length;
  },
  isObj(o: Object) {
    return Object.prototype.toString.call(o) === '[object Object]';
  },
  isString(o: string) {
    return Object.prototype.toString.call(o) === '[object String]';
  },
  getDataByModel(data: any, model: any) {
    // const blackLists = {
    //   password: true,
    // };
    const ret: any = {};
    Object.keys(model).forEach(d => {
      // if (!!blackLists[d]) {
      //   return;
      // }
      ret[d] = data[d];
    });
    ret['id'] = data._id.toString();
    return ret;
  },
  // deprecated
  filterData(data: any) {
    return data;
  },
  isEmail(v: string) {
    return reg.email.test(v);
  },
  isPhone(v: string) {
    return reg.phone.test(v);
  },
  isArray(o: Array<any>) {
    return Object.prototype.toString.call(o) === '[object Array]';
  },
  //username 转化 为 key value   key => email | phone
  formatUsername(username: string) {
    if (this.isEmail(username)) {
      return { email: username };
    }
    if (this.isPhone(username)) {
      return { phone: username };
    }
    return {};
  },
  map(o: Object[] | Array<any>, fn: Function) {
    const retArr = [];
    if (this.isArray(o)) {
      for (let i: number = 0; i < o.length; i++) {
        retArr.push(o[i]);
        fn(o[i], i);
      }
      return retArr;
    }
    const retO: any = {};
    if (this.isObj(o)) {
      for (const key in o) {
        retO[key] = o[key];
        fn(o[key], key);
      }
      return retO;
    }
  },
  sendMsg(phone: string, title: string, content: string) {
    const appid = msgConfig.appId;
    const appkey = msgConfig.appKey;
    const phoneNumbers = [phone];
    const templId = 7839;
    const qcloudsms = QcloudSms(appid, appkey);

    return new Promise((resolve, reject) => {
      // 请求回调处理, 这里只是演示，用户需要自定义相应处理回调
      function callback(err: any, res: any, resData: any) {
        if (err) {
          console.log('msg err: ', err);
          reject(err);
        } else {
          resolve(resData);
          console.log('msg response data: ', resData);
        }
      }
      const ssender = qcloudsms.SmsSingleSender();
      ssender.send(0, 86, phoneNumbers[0], content, '', '', callback);
    });
  },
  getCode() {
    const min = 10000000000;
    const max = 99999999999;
    return (Math.floor(Math.random() * (max - min + 1) + min) + '').slice(0, 6);
  },
  // utils.sendEmail('986171791@qq.com','test title','test content');
  sendEmail(email: string, title: string, content: string) {
    const transporter = nodemailer.createTransport(
      {
        host: emailConfig.host,
        // port: '465',
        // secure: true,
        secureConnection: true,
        auth: {
          user: emailConfig.sender,
          pass: emailConfig.pwd,
        },
        logger: false,
        debug: false, // include SMTP traffic in the logs
      },
      {
        // default message fields

        // sender info
        from: emailConfig.sender,
        headers: {
          // 'X-Laziness-level': 1000 // just an example header, no need to use this
        },
      },
    );

    // Message object
    const message = {
      // Comma separated list of recipients
      to: email,

      // Subject of the message
      subject: title,

      // plaintext body
      text: content,

      // HTML body
      // html:
      //     '<p><b>Hello</b> to myself <img src="cid:note@example.com"/></p>' +
      //     '<p>Here\'s a nyan cat for you as an embedded attachment:<br/><img src="cid:nyan@example.com"/></p>',

      // An array of attachments
      // attachments: [
      //     // String attachment
      //     {
      //         filename: 'notes.txt',
      //         content: 'Some notes about this e-mail',
      //         contentType: 'text/plain' // optional, would be detected from the filename
      //     },

      //     // Binary Buffer attachment
      //     {
      //         filename: 'image.png',
      //         content: Buffer.from(
      //             'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD/' +
      //                 '//+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4U' +
      //                 'g9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC',
      //             'base64'
      //         ),

      //         cid: 'note@example.com' // should be as unique as possible
      //     },

      //     // File Stream attachment
      //     {
      //         filename: 'nyan cat ✔.gif',
      //         path: __dirname + '/assets/nyan.gif',
      //         cid: 'nyan@example.com' // should be as unique as possible
      //     }
      // ]
    };

    return transporter.sendMail(message, (error: any, info: any) => {
      if (error) {
        return process.exit(1);
      }
      // only needed when using pooled connections
      transporter.close();
    });
  },
  delKeyVal(o: any, k: string | number) {},
};
